import xph from '@/common/xph.js'
export default {
	namespaced: true,
    state: {
		// [{
		// 	"id": 16069132,
		// 	"name": "app测试",
		// 	"remark": null,
		// 	"address": 0,
		// 	"interval": 1,
		// 	"sensors": [{
		// 		"num": 0,
		// 		"index": 101,
		// 		"name": "大气温度",
		// 		"value": 32767,
		// 		"unit": "℃",
		// 		"prec": 0.1,
		// 		"min": -50,
		// 		"max": 100
		// 	}],
		// 	"valves": [{
		// 		"num": 0,
		// 		"index": 1,
		// 		"name": "1",
		// 		"state": false,
		// 		"loading": false,
		// 		"selected": true
		// 	}]
		// }]
		devices: []
	},
    getters: {

    },
    mutations: {
		setDeviceInfo(state, devices){
			state.devices = devices
		},
		setDeviceRelay(state, param){
			param.valve.state = param.state
		},
		setDeviceRelayLoading(state, param){
			param.valve.loading = param.state
		},
		setDeviceRelaySelected(state, param){
			param.valve.selected = param.selected
		},
		setDeviceReal(state, param){
			param.sensor.value = param.value
		}
    },
    actions: { 
		setDeviceInfo(context, username){
			xph.getDevicesInfo(username).then(async res => {
				context.commit('setDeviceInfo', res)
				context.dispatch('freshDeviceReal')
			})
		},
		setDeviceRelay(context, param){
			context.commit('setDeviceRelay',  param)
		},
		setDeviceRelayLoading(context, param){
			context.commit('setDeviceRelayLoading',  param)
		},
		setDeviceRelaySelected(context, param){
			context.commit('setDeviceRelaySelected',  param)
		},
		freshDeviceReal(context){
			const devices = context.state.devices
			if(devices && devices.length){
				devices.map(async device => {
					const real = await xph.getRealData(device.id);
					device.sensors.forEach(ele => {
						let data = real['e'+(ele.num+1)]
						if(!!data && data !== 0x7fff){
							context.commit('setDeviceReal', {
								sensor: ele,
								value: data * ele.prec
							})
						}
					})
					device.valves.forEach(ele => {
						const bits = parseInt(ele.num / 32);
						const num = ele.num % 32;
						const state = real['j'+(num + 1)];
						if(!!state){
							context.commit('setDeviceRelay', {
								valve: ele,
								state: (state & (1 << bits)) !== 0
							})
						}
					})
				})
			}
		}
    }
}